package com.hdy.javachatroomdemo.Controller;

import com.hdy.javachatroomdemo.Model.*;
import com.hdy.javachatroomdemo.Service.FriendService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/chatRoomUser")
public class FriendController {
    @Autowired
    private UserProperties userProperties;
    @Autowired
    private FriendService friendService;

    @GetMapping("/addFriend")
    public List<Friend> queryFriend(String friendName,@SessionAttribute("USER_SESSION")User user) {
        //前端发来搜索好友的请求后直接返回结果
        return friendService.queryFriend(friendName,user.getUsername(), user.getUserId());
    }

    @RequestMapping("/getFriendRequest")
    //获得历史好友请求
    public List<MessageResponse> queryFriendRequest(@SessionAttribute("USER_SESSION")User user) {
        List<MessageResponse> ret=friendService.queryFriendRequest2(user.getUserId());
        System.out.println(ret);
        return ret;
    }

    //处理接受或拒绝好友请求之后的请求
    @RequestMapping("/clearFriendRequest")
    public void handleFriendRequest(int userId, int status, @SessionAttribute("USER_SESSION")User user) {
        //构造好友请求
        MessageRequest messageRequest = new MessageRequest();
        messageRequest.setType("friendRequest");
        messageRequest.setUserId(userId);
        //这里friendId指的是添加好友的接收方,
        messageRequest.setFriendId(user.getUserId());
        //把好友请求从数据库中删除
        friendService.deleteFriendRequest(messageRequest);
        //判断是接受还是拒绝
        //如果是拒绝不需要额外操作
        if(status==0){
            return;
        }
        //接受好友请求则在数据库中添加好友关系
        friendService.addFriend(messageRequest);
        //还有一种情况,自己给自己添加好友的情况,解决方式是在查询好友的时候不要返回自己


    }

    @GetMapping("/friendList")
    public List<Friend> friendList(HttpServletRequest req){
        //获取session对象
        HttpSession session= req.getSession(false);
        System.out.println("[FriendController:friendList]:会话对象为空");
        if(session==null){
            return new ArrayList<>();
        }
        //获取user对象
        User user=(User)session.getAttribute(userProperties.getSession().getKey());
        if(user==null){
            System.out.println("[FriendController:friendList]:session表中user为空");
            return new ArrayList<>();
        }
        List<Friend> ret= friendService.friendList(user);
        return ret;
//        User newUser=new User();
//        List<User> friendList=new ArrayList<>();
//        friendList.add(user);
//        return friendList;

    }
}
